// V-backend/src/models/Audience.js
const { DataTypes } = require('sequelize');
const bcrypt = require('bcryptjs');

module.exports = (sequelize) => {
  const Audience = sequelize.define('Audience', {
    audience_id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    audience_name: {
      type: DataTypes.STRING(50),
      allowNull: false
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: true,
      unique: true,
      validate: {
        isEmail: true
      }
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: false
    },
    gender: {
      type: DataTypes.ENUM('male', 'female', 'unknown'),
      defaultValue: 'unknown'
    },
    avatar: {
      type: DataTypes.STRING(255),
      defaultValue: '/src/assets/images/avatars/default-avatar.png'
    }
  }, {
    tableName: 'v_audience',
    timestamps: true,
    underscored: true,
    hooks: {
      beforeCreate: async (audience) => {
        if (audience.password) {
          audience.password = await bcrypt.hash(audience.password, 10);
        }
      },
      beforeUpdate: async (audience) => {
        if (audience.changed('password')) {
          audience.password = await bcrypt.hash(audience.password, 10);
        }
      }
    }
  });

  // 实例方法
  Audience.prototype.validatePassword = async function(password) {
    return await bcrypt.compare(password, this.password);
  };

  Audience.prototype.toSafeObject = function() {
    const values = { ...this.get() };
    delete values.password;
    return values;
  };

  // 关联定义
  Audience.associate = function(models) {
    Audience.hasMany(models.Registration, {
      foreignKey: 'audience_id',
      as: 'registrations'
    });
  };

  return Audience;
};